package com.sh15tech.mp.weixin.scan;

import com.sh15tech.mp.weixin.Constants;
import com.sh15tech.mp.weixin.PropKey;
import com.sh15tech.mp.weixin.SysConfig;
import com.sh15tech.mp.weixin.common.HttpHelper;
import com.sh15tech.mp.weixin.common.Tool;
import com.sh15tech.mp.weixin.modal.*;

import java.util.ArrayList;
import java.util.List;

public class WxSender {

	/**
	 * 获取通信凭证
	 */
	public static WxToken getToken(){

		String url = "/token?grant_type=client_credential&appid=%s1%&secret=%s2%";

		url = url.replace("%s1%", SysConfig.get(PropKey.APP_ID));
		url = url.replace("%s2%", SysConfig.get(PropKey.APP_SECRET));

		return (WxToken)Tool.toObj(HttpHelper.get(url), WxToken.class);
	}
	
	/**
	 * 获取通信凭证
	 */
	public static WxToken getToken(String appid, String secret){
		
		String url = "/token?grant_type=client_credential&appid=%s1%&secret=%s2%";
		
		url = url.replace("%s1%", appid);
		url = url.replace("%s2%", secret);
		
		return (WxToken)Tool.toObj(HttpHelper.get(url), WxToken.class);
	}
	
//	public static void getJsApi(String token){
//		String url = "/ticket/getticket?access_token="+token+"&type=jsapi";
//		Client.get(url);
//	}
	
	/**
	 * 获取用户列表
	 * @return
	 */
	public static List<WxUserDetail> getUsers(){
		
		waitToken();
		
		String url = "/user/get?access_token="+Constants.PLACEHOLDER_TOKEN;
		
		List<WxUserDetail> list = new ArrayList<>();
		
		WxUsers wu = (WxUsers)Tool.toObj(HttpHelper.get(url), WxUsers.class);
		
		if(wu.getErrcode() == null){
			List<String> result = new ArrayList<>();
			
			if(wu.getData() != null && wu.getData().getOpenid() != null){
				for(String str : wu.getData().getOpenid()){
					result.add(str);
				}
			}
			
			if(!Tool.isEmpty(wu.getNext_openid())){
				getUsers(url, wu.getNext_openid(), result);
			}
			
			for(String openid : result){
				WxUserDetail wud = getUserDetail(openid);
				if(wud.getErrcode() == null){
					list.add(wud);
				}
			}
		}
		
		return list;
	}
	
	/**
	 * 获取用户列表
	 * @param url
	 * @param nextId
	 * @param result
	 */
	private static void getUsers(String url, String nextId, List<String> result){
		
		if(!Tool.isEmpty(nextId)){
			WxUsers wu = (WxUsers)Tool.toObj(HttpHelper.get(url+"&next_openid="+nextId), WxUsers.class);
			
			if(wu.getData() != null && wu.getData().getOpenid() != null){
				for(String str : wu.getData().getOpenid()){
					result.add(str);
				}
			}
			
			if(!Tool.isEmpty(wu.getNext_openid())){
				getUsers(url, wu.getNext_openid(), result);
			}
		}
		
	}
	
	/**
	 * 获取用户基本信息
	 * @param openid
	 * @return
	 */
	private static WxUserDetail getUserDetail(String openid){
		
		waitToken();
		
		String url = "/user/info?access_token="+Constants.PLACEHOLDER_TOKEN+"&openid="+openid;
		
		return (WxUserDetail)Tool.toObj(HttpHelper.get(url), WxUserDetail.class);
	}
	
	/**
	 * 发送转正提醒
	 * @param msg
	 * @return
	 */
	public static boolean enrollment(WxMessage msg){
		
		waitToken();
		
		String url = "/message/template/send?access_token="+Constants.PLACEHOLDER_TOKEN;
		
		String paras = "{\"touser\":\"%open_id%\",\"template_id\":\"%template_id%\",\"url\":\"%url%\","
				+ "\"data\":{\"first\":{\"value\":\"%first%\",\"color\":\"%color%\"},"
				+ "\"keyword1\":{\"value\":\"%keyword1%\",\"color\":\"%color%\"},"
				+ "\"keyword2\":{\"value\":\"%keyword2%\",\"color\":\"%color%\"},"
				+ "\"remark\":{\"value\":\"%remark%\",\"color\":\"%color%\"}}}";
		
		paras = paras.replace("%open_id%", msg.getOpenId())
				.replace("%template_id%", SysConfig.get(PropKey.MSG_TEMPLATE_ENROLLMENT))
				.replace("%url%", "")
				.replace("%first%", msg.getMsgContent()+Constants.LINE_BREAK)
				.replace("%keyword1%", Tool.isEmpty(msg.getMsgTitle())?"正常转正":msg.getMsgTitle())
				.replace("%keyword2%", Tool.date2cn(msg.getEnrollmentTime()))
				.replace("%remark%", "")
				.replaceAll("%color%", "#173177");
		
		WxResponse res = (WxResponse)Tool.toObj(HttpHelper.post(url, paras), WxResponse.class);

		return Tool.isEmpty(res.getErrcode());
	}
	
	
	/**
	 * 生成二维码
	 * @param str
	 * @return
	 */
	public static WxQRcode generateQRcode(String str){
		
		waitToken();
		
		String url = "/qrcode/create?access_token="+Constants.PLACEHOLDER_TOKEN;
		
		String paras = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \""+str+"\"}}}";
		
		return (WxQRcode)Tool.toObj(HttpHelper.post(url, paras), WxQRcode.class);
	}
	
	private static void waitToken(){
		while(SysConfig.reqToken){
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
	
	// ----------------------------------------------------------------------------------------
	
	
	
}
